package com.gly091020.mixin;

import com.gly091020.MathDragon;
import com.gly091020.NetWorkingPackId;
import net.fabricmc.fabric.api.networking.v1.PacketByteBufs;
import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking;
import net.minecraft.entity.AreaEffectCloudEntity;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.boss.dragon.EnderDragonEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.projectile.DragonFireballEntity;
import net.minecraft.entity.projectile.ExplosiveProjectileEntity;
import net.minecraft.network.PacketByteBuf;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.util.hit.HitResult;
import net.minecraft.util.math.Box;
import net.minecraft.util.math.random.Random;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Redirect;

import java.util.List;


@Mixin(DragonFireballEntity.class)
public class DragonFireballEntityMixin {
    @Unique
    private Box box;

    @Redirect(method = "onCollision", at = @At(value = "INVOKE", target = "Lnet/minecraft/entity/projectile/ExplosiveProjectileEntity;onCollision(Lnet/minecraft/util/hit/HitResult;)V"))
    public void getThis(ExplosiveProjectileEntity instance, HitResult hitResult){
        box = instance.getBoundingBox();
    }

    @Redirect(method = "onCollision", at = @At(value = "INVOKE", target = "Lnet/minecraft/entity/AreaEffectCloudEntity;setOwner(Lnet/minecraft/entity/LivingEntity;)V"))
    public void setMathWindow(AreaEffectCloudEntity instance, LivingEntity owner){
        instance.setOwner(owner);
        if (!MathDragon.CONFIG.useMathDragon || !MathDragon.CONFIG.switchFunction.dragonBall){return;}
        if (!(owner instanceof EnderDragonEntity)){return;}
        if (owner.getWorld().isClient){return;}
        instance.setRadius(3.0F);
        List<PlayerEntity> playerEntityList = instance.getWorld().getNonSpectatingEntities(PlayerEntity.class, box.expand(4.0, 2.0, 4.0));
        if (!playerEntityList.isEmpty()){
            int i = Random.create().nextBetween(0, playerEntityList.size() - 1);
            PacketByteBuf buf = PacketByteBufs.create();
            buf.writeInt(instance.getId());
            ServerPlayNetworking.send((ServerPlayerEntity) playerEntityList.get(i), NetWorkingPackId.ToPlayer, buf);
        }
    }
}
